import { authAPI } from '@/api/auth'

// 安全的JSON解析函数
const safeJsonParse = (str, defaultValue) => {
  try {
    const item = localStorage.getItem(str)
    if (item === null || item === 'undefined' || item === 'null') {
      return defaultValue
    }
    return JSON.parse(item)
  } catch (error) {
    console.warn(`Failed to parse localStorage item "${str}":`, error)
    return defaultValue
  }
}

const state = {
  token: localStorage.getItem('token') || '',
  userInfo: safeJsonParse('userInfo', {}),
  roles: safeJsonParse('roles', [])
}

const mutations = {
  SET_TOKEN(state, token) {
    state.token = token
    localStorage.setItem('token', token)
  },

  SET_USER_INFO(state, userInfo) {
    state.userInfo = userInfo
    localStorage.setItem('userInfo', JSON.stringify(userInfo))
  },

  SET_ROLES(state, roles) {
    state.roles = roles
    localStorage.setItem('roles', JSON.stringify(roles))
  },

  CLEAR_USER_DATA(state) {
    state.token = ''
    state.userInfo = {}
    state.roles = []
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')
    localStorage.removeItem('roles')
  }
}

const actions = {
  // 用户登录
  async login({ commit }, loginForm) {
    try {
      const response = await authAPI.login(loginForm)
      const { token, username, realName, roles, userId } = response.data

      commit('SET_TOKEN', token)

      // 构造用户信息对象
      const userInfo = {
        id: userId,
        username,
        realName
      }
      commit('SET_USER_INFO', userInfo)

      // 设置用户角色
      commit('SET_ROLES', roles || [])

      return response
    } catch (error) {
      throw error
    }
  },

  // 获取用户信息
  async getUserInfo({ commit, state }) {
    try {
      const response = await authAPI.getCurrentUser()
      const user = response.data

      commit('SET_USER_INFO', user)

      // 提取用户角色
      // 后端返回的roles可能是字符串数组或对象数组，需要兼容处理
      let roles = []
      if (user.roles) {
        if (Array.isArray(user.roles)) {
          // 如果是字符串数组，直接使用
          if (typeof user.roles[0] === 'string') {
            roles = user.roles
          } else {
            // 如果是对象数组，提取roleName
            roles = user.roles.map(role => role.roleName || role.name || role)
          }
        }
      }
      commit('SET_ROLES', roles)

      return user
    } catch (error) {
      throw error
    }
  },

  // 用户登出
  async logout({ commit }) {
    try {
      await authAPI.logout()
    } catch (error) {
      console.error('登出请求失败:', error)
    } finally {
      commit('CLEAR_USER_DATA')
    }
  },

  // 清除用户数据
  clearUserData({ commit }) {
    commit('CLEAR_USER_DATA')
  }
}

const getters = {
  token: state => state.token,
  userInfo: state => state.userInfo || {},
  roles: state => state.roles || [],
  userId: state => (state.userInfo || {}).id,
  username: state => (state.userInfo || {}).username,
  realName: state => (state.userInfo || {}).realName,
  isLoggedIn: state => !!state.token,
  isAdmin: state => (state.roles || []).includes('ADMIN'),
  isTeacher: state => (state.roles || []).includes('TEACHER'),
  isStudent: state => (state.roles || []).includes('STUDENT')
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
